/*
 * @Author: wuqingchun
 * @Date: 2024-10-16 16:39:23
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-10-31 20:51:42
 */
#ifndef __NET_TCP_CLIENT_H__
#define __NET_TCP_CLIENT_H__

#include <thread>
#include <netinet/in.h>
#include <sys/time.h>

#include "libnet.h"
#include "net_buffer.h"

#include "net_tcp_connection.h"

#include "net_event_handler.h"

class CNetTCPClient : public INetTCPClient
{
    enum EnumClientState
    {
        CLI_STATE_UINIT,
        CLI_STATE_INIT,
        CLI_STATE_CONNECTING,
        CLI_STATE_CONNECTED,
        CLI_STATE_DISCONNECTED,
    };
public:
    CNetTCPClient(INetEventHandler& refEvHandler, INetTCPConnectionCallback& pobjCallback, const sockaddr_in& refAddr);
    virtual ~CNetTCPClient();

    virtual int32_t Start() override;
    virtual void Stop() override;
    virtual int32_t SendMessage(const void* pData, size_t ulDataLen) override;

private:
    int32_t __CreateSocket();
    int32_t __Connect();
    ssize_t __RecvOne(void* pBuf, size_t ulBufLen);
    void __Recv();

    ssize_t __SendOne(const void* pData, size_t ulDataLen);
    int32_t __Send(const void* pData, size_t ulDataLen);

    void __SendBuffer();

    int32_t __WaitEvent();

    void __AddWEvent();
    void __DeleteWEvent();
    void __AddREvent();
    void __DeleteREvent();

    // 处理可读事件
    void __DealWEvent();
    // 处理可写事件
    void __DealREvent();
 
    void __ConnMgrThreadFunc();
private:
    INetEventHandler& m_refEvHandler;
    INetTCPConnectionCallback& m_refCallback;
    sockaddr_in m_stAddr;
    timeval m_stWaitTimeout = {1, 0};
    std::thread m_objConnMgrThread;
    volatile bool m_bConnMgrRunning = false;
    int m_iSockFd = -1;
    EnumClientState m_enState = CLI_STATE_UINIT;

    fd_set m_stOriginReadSet;
    fd_set m_stOriginWriteSet;
    fd_set m_stTmpReadSet;
    fd_set m_stTmpWriteSet;

    CNetBuffer m_objSndBuffer;
};

#endif //__NET_TCP_CLIENT_H__